package server.base;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName Request
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/3/6
 * @Version 1.0.0
 */
public class HttpRequest {

    private String method; //GET /POST
    private String url;
    private String ip;
    private int port;
    private String contextPath;
    private String servletUrl;
    private InputStream inputStream;

    public String getContextPath() {
        return contextPath;
    }

    public String getServletUrl() {
        return servletUrl;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    public void setServletUrl(String servletUrl) {
        this.servletUrl = servletUrl;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public HttpRequest() {
    }

    public HttpRequest(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);
        String inputStr = new String(bytes);

        //读取第一行
        String first = inputStr.split("\\n")[0];
        this.method = first.split(" ")[0];
        this.url = first.split(" ")[1];
        int index = url.indexOf("/", 1);
        this.contextPath = url.substring(0,index);
        this.servletUrl = url.substring(index,url.length());


        //读取第二行，获取host
        String second = inputStr.split("\\n")[1];
        this.ip = second.split(":")[1].trim();
        this.port = Integer.parseInt(second.split(":")[2].trim());
    }

}
